import bcrypt from 'bcryptjs'
import db from '../db/index.js'
import jwt from 'jsonwebtoken'
import jwtkey from '../tokenkey/index.js'
export function login(req, res) {
    const { account, password, role } = req.body
    function getid(role) {
        let id = ''
        switch (role) {
            case 'student': return id = 'stuid';
            case 'teacher': return id = 'teacherid';
            case 'admin': return id = 'adminid';
        }
        return id
    }
    const id = getid(role)
    const sql1 = `select * from ${role} where ${id}=? `
    db.query(sql1, [account], (err, data) => {
        if (err) return res.dbno(err)
        if (data.length === 0) return res.cc(198, '账号不存在')
        const user = data[0]
        if (user.islogin == 0) {
            if (user.password != password) return res.cc(198, '密码错误')
        }
        else {
            // 拿着用户输入的密码,和数据库中存储的密码进行对比
            const compareResult = bcrypt.compareSync(password, user.password)
            if (!compareResult) return res.cc(197, '密码错误')
        }
        if (role == 'student') {
            let tecid = null
            const sql3 = 'select teacherid from submajor where submajorid =?'
            db.query(sql3, user.subid, (err, data) => {
                if (err) return res.dbno(err)
                tecid = data[0].teacherid
                const userinfo = { ...user, password: '', tecid }
                //生成token
                const tokenStr = jwt.sign(userinfo, jwtkey, {
                    expiresIn: '7h'
                })
                //发送数据
                return res.send({
                    status: 200,
                    message: '登录成功',
                    data: { ...userinfo },
                    token: 'Bearer ' + tokenStr
                })
            })
        }
        else {
            const userinfo = { ...user, password: '' }
            //生成token
            const tokenStr = jwt.sign(userinfo, jwtkey, {
                expiresIn: '7h'
            })
            //发送数据
            return res.send({
                status: 200,
                message: '登录成功',
                data: { ...userinfo },
                token: 'Bearer ' + tokenStr
            })
        }

    })
}
